<script setup lang="ts">
import { computed, onMounted, provide, reactive, ref } from "vue";
import { storeToRefs } from "pinia";
import useAddressStore from "@/pinia/modules/addressStore.ts";
import { useCascaderAreaData } from "@vant/area-data";
import type { Address } from "@/types/addressTypes";
import type { Ref } from "vue";
import { CascaderOption, showFailToast, showSuccessToast } from "vant";
import AddressList from "@/views/address/components/addressList/addressList.vue";
import Add from "@/views/patient/components/Add/Add.vue";
import Tip from "@/views/patient/components/Tip/Tip.vue";
const addressStore = useAddressStore();
const { addressList, showPopup, edit } = storeToRefs(addressStore);
/*获取地址详情的回调函数*/
const findAddressDetail = async (addressId: string) => {
    try {
        const { receiver, mobile, provinceCode, cityCode, countyCode, province, city, county, addressDetail, isDefault, id } = await addressStore.findAddressDetail(addressId);
        Object.assign(formDate, { receiver, mobile, provinceCode, cityCode, countyCode, addressDetail, isDefault, id });
        fieldValue.value = `${province}-${city}-${county}`;
        cascaderValue.value = `${provinceCode}${cityCode}${countyCode}`;
    } catch (error: any) {
        showFailToast(error.message);
    }
};
/*使用provide将addressList提供给所有子组件进行消费数据*/
provide<Ref<Address[]>>("addressList", addressList);
/*/*使用provide将findAddressDetail提供给所有子组件进行调用*/
provide("findAddressDetail", findAddressDetail);
/*是否显级联选择器弹层*/
const showCascader = ref<boolean>(false);
/*选择的省市区*/
const fieldValue = ref<string>("");
/*选择的省市区编码*/
const cascaderValue = ref<string>("");
/*省市区的数据*/
const options: CascaderOption[] = useCascaderAreaData();
/*表单数据对象*/
const formDate = reactive<Address>({
    mobile: "",// 收货人姓名
    receiver: "", // 联系方式
    provinceCode: "", // 所在省份编码
    cityCode: "", // 所在市编码
    countyCode: "", // 所在区县编码
    addressDetail: "", // 详细地址
    isDefault: 0, // 是否为默认地址
});
/*通过计算属性的可读可写的特性计算出是否为默认地址*/
const isDefault = computed<boolean>({
    get() {
        return formDate.isDefault === 0 ? false : true;
    },
    set(value: boolean) {
        formDate.isDefault = value ? 1 : 0;
    },
});
/*添加地址的标题还是编辑地址的标题*/
const title = computed<string>(() => edit.value ? "编辑地址" : "添加地址");
/*级联选择器全部选项选择完成后触发的回调函数*/
const onFinish = ({ selectedOptions }: { selectedOptions: any }) => {
    showCascader.value = false;
    fieldValue.value = selectedOptions.map((option: any) => option.text).join("-");
};
/*添加地址的回调函数*/
const handleAdd = () => {
    addressStore.changeShowPopup(true);
    addressStore.changeEdit(false);
};
/*获取省市区编码的回调函数*/
const saveCityData = () => {
    const provinc: string = cascaderValue.value.slice(0, 2);
    const city: string = cascaderValue.value.slice(2, 4);
    const county: string = cascaderValue.value.slice(4, 6);
    formDate.provinceCode = provinc;
    formDate.cityCode = city;
    formDate.countyCode = county;
};
/*表单提交的回调函数*/
const handleSubmit = async () => {
    if (edit.value) {
        try {
            saveCityData();
            const { mobile, receiver, provinceCode, cityCode, countyCode, addressDetail, isDefault } = formDate;
            await addressStore.editAddress(formDate.id!, { mobile, receiver, provinceCode, cityCode, countyCode, addressDetail, isDefault });
            await addressStore.fetchAddressList();
            showSuccessToast("修改地址成功");
            addressStore.changeShowPopup(false);
        } catch (error: any) {
            showFailToast(error.message);
        }
    } else {
        try {
            saveCityData();
            delete formDate.id;
            await addressStore.addAddress(formDate);
            await addressStore.fetchAddressList();
            showSuccessToast("添加地址成功");
            addressStore.changeShowPopup(false);
        } catch (error: any) {
            showFailToast(error.message);
        }
    }
};

/*弹出层组件关闭动画结束的回调函数*/
const closedPopup = () => {
    Object.assign(formDate, {
        mobile: "",// 收货人姓名
        receiver: "", // 联系方式
        provinceCode: "", // 所在省份编码
        cityCode: "", // 所在市编码
        countyCode: "", // 所在区县编码
        addressDetail: "", // 详细地址
        isDefault: 0, // 是否为默认地址
    });
    cascaderValue.value = "";
    fieldValue.value = "";
};

onMounted(() => {
    addressStore.fetchAddressList();
});

</script>

<template>
    <div class="address">
        <nav-bar title="地址列表" fixed left-arrow left-text="返回" @click-left=$router.back()></nav-bar>
        <address-list></address-list>
        <Add text="添加地址" @click="handleAdd"></Add>
        <Tip text="最多添加20个地址"></Tip>
        <van-popup v-model:show="showPopup" position="right" :style="{width:'100%',height:'100%'}" @closed="closedPopup">
            <nav-bar :title="title" left-arrow @click-left="addressStore.changeShowPopup(false)"></nav-bar>
            <van-form label-width="40px" @submit="handleSubmit">
                <van-cell-group inset>
                    <van-field label="姓名" placeholder="请输入收货人姓名" v-model="formDate.receiver" />
                    <van-field label="手机" placeholder="请输入收货人手机" v-model="formDate.mobile" />
                    <van-field label="地址" placeholder="请输入收货人详细地址" v-model="formDate.addressDetail" />
                    <van-field v-model="fieldValue" readonly label="地区" placeholder="请选择所在地区" @click="showCascader=true">
                        <template #right-icon>
                            <svg-icon svg-name="address"></svg-icon>
                        </template>
                    </van-field>
                    <van-field label="默认">
                        <template #input>
                            <van-switch size="20px" v-model="isDefault"></van-switch>
                        </template>
                    </van-field>
                </van-cell-group>
                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit">保存</van-button>
                </div>
            </van-form>
            <van-popup v-model:show="showCascader" round position="bottom">
                <van-cascader v-model="cascaderValue" title="请选择所在地区" :options="options" @close="showCascader = false" @finish="onFinish" />
            </van-popup>
        </van-popup>
    </div>
</template>

<style scoped lang="scss">
.address {
    padding: 60px 15px 15px 15px;
}
</style>
